package ${packageName}.mvp.model.api;

import android.util.Log;

import com.jpxx.base.http.response.APIError;
import com.jpxx.lib.klog.KLog;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class ApiObserver<T> implements Observer<T> {
    @Override
    public void onSubscribe(Disposable d) {
        //do nothing, use RxLifecycle auto-dispose.
    }

    @Override
    public void onNext(T t) {
        success(t);
    }

    @Override
    public void onError(Throwable throwable) {
        KLog.e("ApiObserver", "throwable is" + throwable + " , cause by " + Log.getStackTraceString(throwable));

        if(throwable instanceof APIError){
            dealError((APIError) throwable);
        } else{
            //send custom apiError to child, else child cannot receive error.
            dealError(new APIError.NormalAPIException(throwable.getMessage(), throwable.getCause()));
        }
    }

    @Override
    public void onComplete() {
    }

    public abstract void success(T t);

    public void dealError(APIError apiError){

    }
}
